<template>
  <div class="profile" v-loading="loading">
    <div class="profile-header">
      <div class="avatar-section">
        <el-avatar :size="100" :src="userInfo.picUrl || defaultAvatar" @error="handleAvatarError" />
        <el-button type="primary" @click="changeAvatar">更换头像</el-button>
      </div>
      <div class="basic-info">
        <h2>{{ userInfo.username }}</h2>
        <p v-if="userInfo.introduction">{{ userInfo.introduction }}</p>
        <p v-else class="no-intro">暂无个人介绍</p>
        <div class="user-stats">
          <span>注册时间: {{ formatDate(userInfo.createTime) }}</span>
        </div>
      </div>
    </div>

    <el-tabs v-model="activeTab" class="profile-tabs">
      <el-tab-pane label="基本信息" name="basic">
        <el-form
            :model="profileForm"
            :rules="rules"
            ref="profileFormRef"
            label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="profileForm.username"/>
          </el-form-item>

          <el-form-item label="性别">
            <el-radio-group v-model="profileForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="profileForm.email" />
          </el-form-item>

          <el-form-item label="生日">
            <el-date-picker
                v-model="profileForm.birth"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="个人介绍">
            <el-input
                v-model="profileForm.introduction"
                type="textarea"
                :rows="4"
                placeholder="请输入个人介绍"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updateProfile" :loading="updating">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="password">
        <el-form
            :model="passwordForm"
            :rules="passwordRules"
            ref="passwordFormRef"
            label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
            />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="updatePassword" :loading="updating">修改密码</el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 头像上传对话框 -->
    <el-dialog
        title="更换头像"
        v-model="avatarDialogVisible"
        width="400px"
    >
      <div class="avatar-upload-container">
        <el-upload
            class="avatar-uploader"
            drag
            :action="uploadAvatarUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { updateUserInfo } from '@/services/auth'
import { ElMessage } from 'element-plus'
import defaultAvatarImage from '@/assets/img/user-default.png'

export default {
  name: 'Profile',
  setup() {
    const userStore = useUserStore()
    const profileFormRef = ref(null)
    const passwordFormRef = ref(null)

    // 数据状态
    const loading = ref(false)
    const updating = ref(false)
    const activeTab = ref('basic')
    const avatarDialogVisible = ref(false)
    const defaultAvatar = defaultAvatarImage

    // 上传相关配置
    const uploadAvatarUrl = '/api/consumer/updateAvatar'
    const uploadHeaders = {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }

    // 用户信息
    const userInfo = ref({
      username: '',
      sex: 1,
      email: '',
      birth: '',
      introduction: '',
      createTime: '',
      picUrl: ''
    })

    // 表单数据
    const profileForm = reactive({
      username: '',
      sex: 1,
      email: '',
      birth: '',
      introduction: ''
    })

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 表单验证规则
    const rules = {
      email: [
        { required: false, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
      ]
    }

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    }

    // 确认密码验证
    function validateConfirmPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        loading.value = true
        // 从store获取用户信息
        await userStore.fetchUserInfo()
        const user = userStore.userInfo

        userInfo.value = {
          username: user.username,
          sex: user.sex,
          email: user.email,
          birth: user.birth,
          introduction: user.introduction,
          createTime: user.createTime,
          picUrl: user.picUrl
        }

        // 同步到表单
        Object.assign(profileForm, {
          username: user.username,
          sex: user.sex !== undefined ? user.sex : 1,
          email: user.email || '',
          birth: user.birth || '',
          introduction: user.introduction || ''
        })
      } catch (error) {
        ElMessage.error('获取用户信息失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 更新用户信息
    const updateProfile = () => {
      profileFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            updating.value = true

            await updateUserInfo(profileForm)
            ElMessage.success('信息更新成功')
            // 更新store中的用户信息
            await userStore.fetchUserInfo()
            // 重新获取用户信息
            await fetchUserInfo()
          } catch (error) {
            ElMessage.error('更新失败: ' + error.message)
          } finally {
            updating.value = false
          }
        }
      })
    }

    // 修改密码
    const updatePassword = () => {
      passwordFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            updating.value = true

            ElMessage.success('密码修改成功')
            resetPasswordForm()
          } catch (error) {
            ElMessage.error('修改失败: ' + error.message)
          } finally {
            updating.value = false
          }
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(profileForm, {
        sex: userInfo.value.sex !== undefined ? userInfo.value.sex : 1,
        email: userInfo.value.email || '',
        birth: userInfo.value.birth || '',
        introduction: userInfo.value.introduction || ''
      })
    }

    // 重置密码表单
    const resetPasswordForm = () => {
      passwordFormRef.value.resetFields()
    }

    // 更换头像
    const changeAvatar = () => {
      avatarDialogVisible.value = true
    }

    // 处理头像加载错误
    const handleAvatarError = () => {
      return true
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    }

    // 头像上传前检查
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!')
      }

      return isJPG && isLt2M
    }

    // 头像上传成功处理
    const handleAvatarSuccess = (response, file) => {
      if (response.code === '1') {
        ElMessage.success('头像更新成功')
        avatarDialogVisible.value = false
        // 更新用户信息
        fetchUserInfo()
      } else {
        ElMessage.error(response.msg || '头像更新失败')
      }
    }

    // 头像上传失败处理
    const handleAvatarUploadError = (error) => {
      ElMessage.error('头像上传失败: ' + error.message)
    }

    // 初始化加载
    onMounted(() => {
      fetchUserInfo()
    })

    return {
      loading,
      updating,
      activeTab,
      avatarDialogVisible,
      defaultAvatar,
      uploadAvatarUrl,
      uploadHeaders,
      userInfo,
      profileForm,
      passwordForm,
      rules,
      passwordRules,
      profileFormRef,
      passwordFormRef,
      updateProfile,
      updatePassword,
      resetForm,
      resetPasswordForm,
      changeAvatar,
      handleAvatarError,
      formatDate,
      beforeAvatarUpload,
      handleAvatarSuccess,
      handleAvatarUploadError
    }
  }
}
</script>

<style scoped>.profile {
  padding: 20px;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.profile-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.avatar-section {
  text-align: center;
}

.avatar-section .el-avatar {
  margin-bottom: 15px;
}

.basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.basic-info p {
  margin: 0 0 10px 0;
  color: #666;
}

.no-intro {
  color: #999;
  font-style: italic;
}

.user-stats {
  color: #999;
  font-size: 14px;
}

.profile-tabs {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.profile-tabs :deep(.el-tabs__content) {
  padding: 20px;
}

.avatar-upload-container {
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}
</style>
